package com.wangsd.common.component;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.wangsd.web.face.entity.ServiceBusiness;
import com.wangsd.web.face.mapper.ServiceBusinessMapper;
import com.wangsd.web.face.service.ServiceBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class WeixinPayService {
    @Value("${wx.pay.appId}")
    private String appId;
    @Value("${wx.pay.mchId}")
    private String mchId;
    @Value("${wx.pay.mchKey}")
    private String mchKey;
    @Value("${wx.pay.keyPath}")
    private String keyPath;

    @Autowired
    ServiceBusinessService serviceBusinessService;

    /**
     * 扩展方法
     * @param code 层级code 获取服务商
     * @param subMchId 微信子商户id
     * @return
     */
    public WxPayServiceExt getServiceExt(String code, String subMchId) {
        //不使用配置文件配置的参数
        if (code != null) {
            ServiceBusiness business = serviceBusinessService.selectBusinessByCode(code);
            mchId = business.getWxMchId();
            mchKey = business.getWxMchKey();
            appId = business.getWxAppId();
            keyPath = business.getWxKeyPath();
        }
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(appId);
        payConfig.setMchId(mchId);
        payConfig.setMchKey(mchKey);
        payConfig.setKeyPath(keyPath);
        if (subMchId != null) {
            payConfig.setSubMchId(subMchId);
        }

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayServiceExt wxPayService = new WxPayServiceExtImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }


    /**
     * 扩展方法
     * @param businessId 服务商id
     * @param subMchId 微信子商户id
     * @return
     */
    public WxPayServiceExt getService(String businessId, String subMchId) {
        //不使用配置文件配置的参数
        ServiceBusiness business = serviceBusinessService.getById(businessId);
        mchId = business.getWxMchId();
        mchKey = business.getWxMchKey();
        appId = business.getWxAppId();
        keyPath = business.getWxKeyPath();
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(appId);
        payConfig.setMchId(mchId);
        payConfig.setMchKey(mchKey);
        payConfig.setKeyPath(keyPath);
        if (subMchId != null) {
            payConfig.setSubMchId(subMchId);
        }
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayServiceExt wxPayService = new WxPayServiceExtImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }
}
